package com.villaday.idf.activity;

import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.adapter2.HomeTeMaiSearchAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.model2.ChaozhiTemaiHistory;
import com.villaday.idf.model2.Search_type;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DbHomeTeMaiHistoryUtils;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnEditorAction;

public class Home_temaiSearchActivity<T> extends BaseActivity implements OkHttpUtil.OnDataListener, AbsRecyclerViewAdapter.OnItemClickListener {

    @BindView(R.id.toolbar_searchBox)
    public AutoCompleteTextView autoTextView;
    @BindView(R.id.img_delete)
    ImageView imgDelete;
    @BindView(R.id.fl_history)
    TagFlowLayout flHistory;
    @BindView(R.id.ll_delete)
    LinearLayout llDelete;
    @BindView(R.id.rv_search)
    RecyclerView rvSearch;
    @BindView(R.id.img_delete_search)
    ImageView img_delete_search;


    private DbHomeTeMaiHistoryUtils dbInstance;
    private HomeTeMaiSearchAdapter homeTeMaiSearchAdapter;
    private Gson gson = new GsonBuilder().create();

    private List<Search_type.BodyEntity.ItemsEntity> data = new ArrayList<>();

    @Override
    protected int getViewResId() {
        return R.layout.activity_home_temai_search;
    }

    @Override
    protected void init() {
        dbInstance = DbHomeTeMaiHistoryUtils.getInstance();
        List<ChaozhiTemaiHistory> bournSearchhistories = dbInstance.queryDownAllOrderByDate();
        setData(flHistory, llDelete, (List<T>) bournSearchhistories, false);


        rvSearch.setLayoutManager(new LinearLayoutManager(this));
        homeTeMaiSearchAdapter = new HomeTeMaiSearchAdapter(this, rvSearch);
        rvSearch.setAdapter(homeTeMaiSearchAdapter);
        rvSearch.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 0)));
        homeTeMaiSearchAdapter.setOnItemClickListener(this);
        homeTeMaiSearchAdapter.setEmptyView(R.layout.empty_search_tips_white);
        homeTeMaiSearchAdapter.setEmptyTips(R.id.tv_emptyTips, "抱歉，未能搜索到相关内容");
        //homeTeMaiSearchAdapter.setEmptyTips(R.id.tv_emptyTips, "");
        autoTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    List<ChaozhiTemaiHistory> bournSearchhistories = dbInstance.queryDownAllOrderByDate();
                    setData(flHistory, llDelete, (List<T>) bournSearchhistories, false);
                    rvSearch.setVisibility(View.INVISIBLE);
                    data.clear();
                    homeTeMaiSearchAdapter.setData(data);

                    img_delete_search.setVisibility(View.GONE);

                } else {
                    img_delete_search.setVisibility(View.VISIBLE);
                    llDelete.setVisibility(View.GONE);
                    homeTeMaiSearchAdapter.setSearchData(s.toString());
                    gotoSearch(s.toString());

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnEditorAction(R.id.toolbar_searchBox)
    public boolean onEditAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            //ToastUtil.initToast(this, "hhhh");
            PhoneUtil.hideKeyboard(v);
            CharSequence text = v.getText();
            if (!TextUtils.isEmpty(text)) {
                dbInstance.insertOrReplace(text.toString(), System.currentTimeMillis());
                List<ChaozhiTemaiHistory> bournSearchhistories = dbInstance.queryDownAllOrderByDate();
                setData(flHistory, llDelete, (List<T>) bournSearchhistories, false);

            }


            return true;
        }
        return false;
    }

    private void setData(final TagFlowLayout fl, LinearLayout ll, final List<T> object, boolean isRetract) {

        if (object == null || object.size() == 0) {
            ll.setVisibility(View.GONE);

        } else {
            ll.setVisibility(View.VISIBLE);

        }
        if (object != null) {
            // ll.setVisibility(View.VISIBLE);
            TagAdapter<T> tagAdapter = new TagAdapter<T>(object) {
                @Override
                public View getView(FlowLayout parent, int position, T s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tv,
                            fl, false);
                    if (s instanceof ChaozhiTemaiHistory) {
                        //当地热门

                        ChaozhiTemaiHistory hot = (ChaozhiTemaiHistory) s;
                        if (hot.getKeyword().length() > 10) {
                            tv.setText(hot.getKeyword().substring(0, 9) + "...");

                        } else {
                            tv.setText(hot.getKeyword());

                        }

                    }


                    return tv;
                }
            };
            fl.setAdapter(tagAdapter);
            fl.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()

            {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {
                    List<ChaozhiTemaiHistory> object1 = (List<ChaozhiTemaiHistory>) object;
                    dbInstance.insertOrReplace(object1.get(position).getKeyword(), System.currentTimeMillis());
                    List<ChaozhiTemaiHistory> bournSearchhistories = dbInstance.queryDownAllOrderByDate();
                    setData(flHistory, llDelete, (List<T>) bournSearchhistories, false);
                    homeTeMaiSearchAdapter.setSearchData(object1.get(position).getKeyword());

                    gotoSearch(object1.get(position).getKeyword());
                    rvSearch.setVisibility(View.VISIBLE);
                    autoTextView.setText(object1.get(position).getKeyword());
                    Editable etext = autoTextView.getText();
                    Selection.setSelection(etext, etext.length());


                    return true;
                }
            });
        } else {
            //ll.setVisibility(View.GONE);

        }


    }

    private void gotoSearch(String keyword) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("keyword", keyword);
        OkHttpUtil.getJSON(this, Constant.URL.search_type, map, this);


    }


    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.search_type.equals(url)) {
                rvSearch.setVisibility(View.VISIBLE);

                LogeUtil.e("search_type", json);
                data.clear();
                Search_type search_type = gson.fromJson(json, Search_type.class);
                if ("200".equals(search_type.getCode())) {
                    data.addAll(search_type.getBody().getItems());
                    llDelete.setVisibility(View.GONE);
                } else {
                    llDelete.setVisibility(View.VISIBLE);

                }

                homeTeMaiSearchAdapter.setData(data);

            }
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }


    @OnClick({R.id.img_delete, R.id.tv_cancle, R.id.img_delete_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_delete_search:
                autoTextView.setText("");
                break;
            case R.id.tv_cancle:
                onBackPressed();
                break;
            case R.id.img_delete:
                dbInstance.deleteAll();
                List<ChaozhiTemaiHistory> bournSearchhistories = dbInstance.queryDownAllOrderByDate();
                setData(flHistory, llDelete, (List<T>) bournSearchhistories, false);
                break;
        }

    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent1 = new Intent(this, HouseDetailsActivityFor3.class);
        intent1.putExtra("houseId", data.get(position).getId());
        intent1.putExtra("persellId", data.get(position).getId());
        intent1.putExtra("presellProduct", true);
//              intent.putExtra("type", data.get(position).getType());
        startActivity(intent1);
    }
}
